
#include "button.h"

void button_scan_tick_handler(BUTTON_STRUCT* button, uint8_t tick)
{
	uint8_t temp_button_state;
	if(button->read_pin_level_config_callback != 0){
		temp_button_state = button->read_pin_level_config_callback(button);

		if(temp_button_state == button->pin_press_level_config){
			temp_button_state = BUTTON_STATE_PRESS;
		}
		else{
			temp_button_state = BUTTON_STATE_RELEASE;
		}

		if(temp_button_state == BUTTON_STATE_RELEASE){
			if(button->state == BUTTON_STATE_RELEASE){
				//button free
			}else{
				if(button->release_event_callback != 0){
					button->release_event_callback(button);
				}
				button->state = BUTTON_STATE_RELEASE;
			}
			button->press_tick_count = 0;
		}
		else{
			if(button->state == BUTTON_STATE_RELEASE){
				if(button->press_tick_count >= button->jitter_tick_config){
					if(button->press_event_callback != 0){
						button->press_event_callback(button);
					}
					button->state = BUTTON_STATE_PRESS;
				}
			}else if(button->state == BUTTON_STATE_PRESS){
				if(button->press_tick_count >= button->long_press_tick_config){
					if(button->long_press_event_callback != 0){
						button->long_press_event_callback(button);
					}
					button->press_tick_count = 0;
					button->state = BUTTON_STATE_LONG_PRESS;
				}
			}
			else{	//button long press repeat
				if(button->press_tick_count >= button->long_press_repeat_tick_config){
					if(button->long_press_repeat_event_callback != 0){
						button->long_press_repeat_event_callback(button);
					}
					button->press_tick_count = 0;
				}
			}
			button->press_tick_count += tick;
		}
	}
}
